<template>
  <div class="app-container">
    <div v-if="isOrderManagement">
      <ViewSessions
        class="sousuo"
        style="margin-bottom: 15px"
        @selected="selected"
        @add="add"
        @importFile="importFile"
      />
      <el-table
        border
        :row-class-name="tableRowClassName"
        :data="orderList"
        :header-row-style="{
          'background-color': '#E6E6E6',
          'font-weight': 'bold',
          color: '#333',
        }"
        :tree-props="{
          children: 'children',
          hasChildren: 'hasChildren',
        }"
        height="650"
        align="center"
        style="width: 100%; margin-bottom: 20px"
        row-key="id"
      >
        <el-table-column
          show-overflow-tooltip
          align="center"
          width="100px"
          prop="id"
          label="订单编号"
        />
        <el-table-column
          show-overflow-tooltip
          align="center"
          width="100px"
          prop="code"
          label="编号"
        />
        <el-table-column align="center" label="订单二维码">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="mini"
              @click="() => seeVueQr(scope.row)"
            >查看
            </el-button>
          </template>
        </el-table-column>
        <el-table-column align="center" label="产品详情">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="mini"
              @click="() => seeOrder(scope.row)"
            >查看
            </el-button>
            <el-button
              type="text"
              size="mini"
              @click="() => uploadZip(scope.row)"
            >上传压缩包
            </el-button>
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          align="center"
          prop="insideCode"
          label="内部编号"
        />

        <el-table-column
          show-overflow-tooltip
          align="center"
          prop="customer"
          label="客户"
        />
        <el-table-column
          show-overflow-tooltip
          align="center"
          prop="deliveryTime"
          label="交货日期"
        />
        <el-table-column
          show-overflow-tooltip
          align="center"
          prop="productAmount"
          label="数量"
        />
        <el-table-column
          show-overflow-tooltip
          align="center"
          prop="picAmount"
          label="图纸数量"
        />
        <!-- <el-table-column show-overflow-tooltip align="center" prop="partsAmount" label="零件总数量"/> -->
        <el-table-column
          show-overflow-tooltip
          align="center"
          prop="totalPrice"
          label="订单总价"
        />
        <el-table-column
          align="center"
          label="订单状态"
          prop="statusName"
        >
          <!-- <template slot-scope="scope">
            <span>{{ scope.row.status == 0 ? '进行中' : '已完成' }}</span>
          </template> -->
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          align="center"
          prop="customer"
          label="客户"
        />
        <!-- <el-table-column align="center" label="状态">
          <template slot-scope="scope">
            <span>{{ scope.row.deleteFlag == 1 ? '删除' : '正常' }}</span>
          </template>
        </el-table-column> -->
        <!-- <el-table-column fixed="right" align="center" label="导入产品">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="mini"
              @click="importFile(scope)"
            >导入
            </el-button>
          </template>
        </el-table-column> -->
        <el-table-column fixed="right" align="center" label="操作">
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.deleteFlag == 1"
              type="text"
              size="mini"
              @click="() => seeDeleteItem(scope.row)"
            >查看
            </el-button>
            <el-button
              v-if="scope.row.deleteFlag != 1 && isRouter"
              type="text"
              size="mini"
              @click="() => upload(scope.row)"
            >修改
            </el-button>
            <el-button
              v-if="scope.row.deleteFlag != 1 && isRouter"
              type="text"
              size="mini"
              @click="() => delect(scope.row)"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :current-page="page"
        :total="total"
        :page-size="limit"
        style="padding: 30px 0; text-align: end"
        layout="total, prev, pager, next,jumper"
        @current-change="fetchData"
      />
    </div>
    <div v-else>
      <orderProductDetails
        :install-id="installId"
        :order-code="orderCode"
        :is-order-product="isOrderProduct"
        @goback="goback"
      />
    </div>
    <el-dialog
      :visible.sync="dialogFormVisible"
      :title="dialogFormValue"
      @close="closeDialog"
    >
      <el-form
        ref="order"
        :model="order"
        :rules="validateRules"
        label-width="120px"
      >
        <el-form-item label="订单编号：" prop="code">
          <el-col :span="8">
            <el-input
              :disabled="readonlyInput"
              v-model="order.code"
              size="small"
              placeholder="请输入订单编号"
            />
          </el-col>
        </el-form-item>

        <el-form-item label="客户：" prop="customer">
          <el-col :span="8">
            <el-input
              :disabled="readonlyInput"
              v-model="order.customer"
              size="small"
              placeholder="请输入客户"
            />
          </el-col>
        </el-form-item>
        <el-form-item label="交货日期：" prop="deliveryTime">
          <el-col :span="6">
            <el-date-picker
              :disabled="readonlyInput"
              v-model="order.deliveryTime"
              value-format="yyyy-MM-dd"
              type="date"
              placeholder="选择交货日期："
            />
          </el-col>
        </el-form-item>
        <el-form-item label="内部编号：" prop="insideCode">
          <el-col :span="8">
            <el-input
              :disabled="readonlyInput"
              v-model="order.insideCode"
              size="small"
              placeholder="请输入内部编号"
            />
          </el-col>
        </el-form-item>
        <!-- <el-form-item label="数量：" prop="amount">
          <el-col :span="8">
            <el-input
              :disabled="readonlyInput"
              v-model.number="order.amount"
              onkeyup="value=value.replace(/[^\d]/g,'')"
              size="small"
              placeholder="请输入数量"
            />
          </el-col>
        </el-form-item>
        <el-form-item label="图纸数量：" prop="imageAmount">
          <el-col :span="8">
            <el-input
              :disabled="readonlyInput"
              v-model.number="order.imageAmount"
              onkeyup="value=value.replace(/[^\d]/g,'')"
              size="small"
              placeholder="请输入图纸数量"
            />
          </el-col>
        </el-form-item>
        <el-form-item label="零件总数量：" prop="partsAmount">
          <el-col :span="8">
            <el-input
              :disabled="readonlyInput"
              v-model.number="order.partsAmount"
              onkeyup="value=value.replace(/[^\d]/g,'')"
              size="small"
              placeholder="请输入零件总数量"
            />
          </el-col>
        </el-form-item> -->
        <el-form-item label="图号：" prop="product">
          <el-col :span="15">
            <el-select
              :disabled="readonlyInput"
              v-model="order.product"
              clearable
              multiple
              placeholder="请选择图号"
              @change="changeProduct"
            >
              <el-option
                v-for="item in productList"
                :key="item.id"
                :label="item.picCode"
                :value="item.id"
              />
            </el-select>
          </el-col>
        </el-form-item>
        <div v-if="productSelectItem.length > 0">
          <div
            v-for="(item, index) in productSelectItem"
            :key="index"
            style="margin-left: 100px"
          >
            <div style="display: inline-flex; margin: 10px">
              <span style="margin: 10px 10px">{{
                item.picCode
              }}</span>
              <el-input
                v-model.number="item.amount"
                onkeyup="value=value.replace(/[^\d]/g,'')"
                placeholder="请输入图号数量"
              />
            </div>
          </div>
        </div>
        <!-- <el-form-item label="订单总价：" prop="price">
          <el-col :span="8">
            <el-input
              :disabled="readonlyInput"
              v-model.number="order.price"
              onkeyup="value=value.replace(/[^\d]/g,'')"
              size="small"
              placeholder="请输入订单总价"
            />
          </el-col>
        </el-form-item> -->
      </el-form>
      <div v-if="!readonlyInput" slot="footer" class="dialog-footer">
        <el-button @click="restData()">取 消</el-button>
        <el-button
          type="primary"
          @click="append('order')"
        >确 定</el-button
        >
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogDelect">
      <el-input
        :rows="2"
        v-model="textDelect"
        type="textarea"
        placeholder="请输入删除理由"
      />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="delectClick">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogVueQr" width="400px">
      <div style="text-align: center; height: 220px">
        <vue-qr
          :size="191"
          :margin="0"
          :auto-color="true"
          :dot-scale="1"
          :text="appSrc"
        />
      </div>
    </el-dialog>

    <el-dialog
      :visible.sync="dialogFileUpload.show"
      :title="isImportExecl ? '导入' : '上传压缩包'"
      width="400px"
    >
      <el-form>
        <el-form-item label="文件上传：">
          <template v-if="dialogFileUpload.fileName.length == 0">
            <el-upload
              :multiple="false"
              :http-request="httpRequest"
              :before-upload="beforeUploadFile"
              action="#"
            >
              <el-button
                size="small"
                type="primary"
              >点击上传</el-button
              >
              <div slot="tip" class="el-upload__tip">
                只能上传{{
                  isImportExecl ? "excel" : zipStr
                }}文件
              </div>
            </el-upload>
          </template>

          <div v-else class="the-file">
            {{ dialogFileUpload.fileName }}
            <el-button
              type="danger"
              size="small"
              class="the-file-delete"
              icon="el-icon-delete"
              @click="removeFile"
            />
          </div>
        </el-form-item>

        <el-form-item>
          <el-button
            :disabled="dialogFileUpload.disabled"
            :loading="dialogFileUpload.loading"
            type="primary"
            @click="confirmUpload"
          >确认上传</el-button
          >
          <el-button @click="closeUploadFileDialog">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

  </div>
</template>

<script>
import orderProductDetails from '../orderProductDetails/index.vue'
import ViewSessions from './ViewSessions.vue'
import user from '../../api/acl/user.js'
const IMPORT_EXECL = 'IMPORT_EXECL' // 导入execl
const UPLOAD_ZIP = 'UPLOAD_ZIP' // 上传压缩包
export default {
  components: {
    ViewSessions,
    orderProductDetails
  },
  data() {
    return {
      installId: '',
      statusMap: {
        0: '未开始',
        1: '进行中',
        2: '已完成'
      },
      // statusMap: {
      //   1: '未开始',
      //   21: '已派单',
      //   22: '已外协',
      //   23: '已派单-已外协',
      //   24: '外协已完成/已到货',
      //   3: '生产中',
      //   4: '待品检',
      //   41: '报废',
      //   42: '可维修',
      //   43: '合格',
      //   44: '不合格',
      //   5: '品检中',
      //   51: '待入库',
      //   6: '入库中',
      //   7: '出库中',
      //   8: '已完成'
      // },
      isOrderProduct: false,
      orderCode: '',
      isOrderManagement: true,
      isRouter: !(
        window.sessionStorage.getItem('department') == 8 ||
					window.sessionStorage.getItem('department') == 10
      ),
      productSelectItem: [],
      productList: [],
      dialogVueQr: false,
      appSrc: '',
      readonlyInput: false,
      dialogDelect: false,
      textDelect: '',
      total: 0, // 数据库中的总记录数
      page: 1, // 默认页码
      limit: 10, // 每页记录数
      validateRules: {
        code: [
          {
            required: true,
            trigger: 'change',
            message: '请输入订单编号'
          }
        ],
        customer: [
          {
            required: true,
            trigger: 'change',
            message: '请输入客户'
          }
        ],
        insideCode: [
          {
            required: true,
            trigger: 'change',
            message: '请输入内部编号'
          }
        ],
        amount: [
          {
            required: true,
            trigger: 'change',
            message: '请输入数量'
          },
          { type: 'number', message: '请输入数字' }
        ],
        imageAmount: [
          {
            required: true,
            trigger: 'change',
            message: '请输入数量'
          },
          { type: 'number', message: '请输入数字' }
        ],
        partsAmount: [
          {
            required: true,
            trigger: 'change',
            message: '请输入数量'
          },
          { type: 'number', message: '请输入数字' }
        ],
        price: [
          {
            required: true,
            trigger: 'change',
            message: '请输入数量'
          },
          { type: 'number', message: '请输入数字' }
        ],
        deliveryTime: [
          {
            required: true,
            message: '请选择交货时间：',
            trigger: 'change'
          }
        ]
      },
      orderList: [],
      dialogFormVisible: false,
      dialogFormValue: '',
      order: {
        code: '',
        insideCode: '',
        customer: '',
        deliveryTime: '',
        amount: '',
        imageAmount: '',
        partsAmount: '',
        price: '',
        product: []
      },
      s1electOrder: {
        orgerId: '',
        insideCode: '',
        deleteFlag: '',
        customer: '',
        status: '',
        valueDtStart:"",
      },
      delectId: '',
      dialogFileUpload: {
        type: IMPORT_EXECL, // upload_zip
        show: false,
        id: '',
        loading: false,
        disabled: false,
        fileName: '',
        code: '',
        formData: null,
        row: {}
      },
      zipType: ['zip', 'rar'],
      excelType: ['xls', 'xlsx']
    }
  },

  computed: {
    isImportExecl() {
      return this.dialogFileUpload.type == IMPORT_EXECL
    },
    isUploadZip() {
      return this.dialogFileUpload.type == UPLOAD_ZIP
    },
    zipStr() {
      return this.zipType.join()
    }
  },
  // 监听上面文本框搜索
  watch: {
    dialogFormVisible(val) {
      console.log(val)
      if (val == true) {
        this.listProduct()
      }
    }
  },

  created() {},
  mounted() {
    this.listOrder()
  },
  methods: {
    changeProduct(val) {
      console.log(val)
      let picCode = ''
      const list = this.productSelectItem
      this.productSelectItem = []

      for (let i = 0; i < val.length; i++) {
        const obj = {}
        if (list.length > 0) {
          const value = list.some((item) => {
            return item.id == val[i]
          })
          if (value) {
            list.some((item) => {
              if (item.id == val[i]) {
                this.productSelectItem.push(item)
              }
            })
          } else {
            this.productList.forEach((item) => {
              if (item.id == val[i]) {
                console.log(item)
                picCode = item.picCode
              }
            })
            obj.id = val[i]
            obj.picCode = picCode
            obj.amount = ''
            this.productSelectItem.push(obj)
          }
        } else {
          this.productList.forEach((item) => {
            if (item.id == val[i]) {
              console.log(item)
              picCode = item.picCode
            }
          })
          obj.id = val[i]
          obj.picCode = picCode
          obj.amount = ''
          this.productSelectItem.push(obj)
        }
      }
      console.log(this.productSelectItem)
    },
    seeVueQr(val) {
      this.dialogVueQr = true
      this.appSrc = val.insideCode + ''
    },
    tableRowClassName({ row, rowIndex }) {
      if (row.deleteFlag == 1) {
        return 'warning-row'
      }
      return ''
    },
    delectClick() {
      if (this.textDelect == '') {
        this.$message({
          message: '请输入删除理由',
          duration: 1000
        })
        return
      }
      user.deleteOrder({
        deleteFlag: 1,
        id: this.delectId,
        deleteRemark: this.textDelect
      }).then((response) => {
        this.delectId = ''
        this.textDelect = ''
        this.dialogDelect = false
        this.$message({
          message: '删除成功',
          duration: 1000
        })
        this.listOrder()
      })
    },
    delect(val) {
      this.delectId = val.id
      this.textDelect = ''
      this.dialogDelect = true
    },
    fetchData(val) {
      this.page = val
      this.listOrder()
    },
    closeDialog() {
      this.order = {
        code: '',
        insideCode: '',
        customer: '',
        deliveryTime: '',
        amount: '',
        imageAmount: '',
        partsAmount: '',
        price: '',
        product: []
      }
      this.productSelectItem = []
      this.$refs.order.resetFields()
    },
    // 产品列表
    listProduct() {
      user.listProductForMenu2({}).then((response) => {
        console.log('listProductForMenu', response)
        this.productList = response
      })
    },
    // 新增，修改，删除
    insertOrder(val) {
      debugger
      if (val.id == '' || val.id == null || val.id == undefined) {
        user.insertOrder(val).then((response) => {
          this.dialogFormVisible = false
          this.$message({
            message: '新增成功',
            duration: 1000
          })
          this.listOrder()
        })
      } else {
        user.updateOrder(val).then((response) => {
          this.dialogFormVisible = false
          this.$message({
            message: '修改成功',
            duration: 1000
          })
          this.listOrder()
        })
      }
    },
    append(val) {
      console.log(this.productSelectItem)
      for (let i = 0; i < this.productSelectItem.length; i++) {
        if (
          this.productSelectItem[i].amount == '' ||
						this.productSelectItem[i].amount == null ||
						this.productSelectItem[i].amount == undefined
        ) {
          this.$message({
            message:
								'请输入图号对应为' +
								this.productSelectItem[i].picCode +
								'的数量',
            duration: 1000
          })
          return
        }
      }
      this.$refs[val].validate((valid) => {
        if (valid) {
          this.insertOrder({
            id: this.order.id,
            productList: this.productSelectItem,
            code: this.order.code,
            insideCode: this.order.insideCode,
            customer: this.order.customer,
            deliveryTime: this.order.deliveryTime
            // amount: this.order.amount,
            // imageAmount: this.order.imageAmount,
            // partsAmount: this.order.partsAmount,
            // price: this.order.price
          })
        }
      })
    },
    restData() {
      this.dialogFormVisible = false
      this.dialogFormValue = ''
    },
    listOrder() {
      let valueDtStart = ""
      let valueDtEnd = ""
      debugger
      if (this.s1electOrder.valueDtStart){
        valueDtStart = this.s1electOrder.valueDtStart[0]
        valueDtEnd = this.s1electOrder.valueDtStart[1]
      }
      user.listOrder({
        code: this.s1electOrder.orgerId,
        insideCode: this.s1electOrder.insideCode,
        deleteFlag: this.s1electOrder.deleteFlag,
        status: this.s1electOrder.status,
        customer: this.s1electOrder.customer
          ? this.s1electOrder.customer
          : null,
        // endDate: this.s1electOrder.endTime,
        limit: this.limit,
        page: this.page,
        valueDtStart:valueDtStart,
        valueDtEnd:valueDtEnd
        // startDate: this.s1electOrder.startTime
      }).then((response) => {
        this.total = response.total
        this.orderList =
						response.list.map((item) => {
						  item.statusName =
								this.statusMap[item.status || ''] || '--'
						  return item
						}) || []
        // this.orderList = response.list
      })
    },
    selected(val) {
      this.s1electOrder = val
      this.page = 1
      this.listOrder()
    },
    add() {
      this.dialogFormVisible = true
      this.dialogFormValue = '新增订单'
      this.readonlyInput = false
    },
    goback() {
      this.isOrderManagement = true
      this.orderCode = ''
      this.isOrderProduct = false
    },
    seeOrder(val) {
      this.isOrderManagement = false
      this.orderCode = val.insideCode
      this.installId = val.id
      this.isOrderProduct = true
      // this.$router.push({ path: '/orderProductDetails', query: { id: val.id, insideCode: val.insideCode }})
    },
    uploadZip(row) {
      this.dialogFileUpload.show = true
      this.dialogFileUpload.type = UPLOAD_ZIP
      this.dialogFileUpload.row = row
      this.dialogFileUpload.disabled = false
    },
    seeDeleteItem(val) {
      this.dialogFormVisible = true
      this.dialogFormValue = '查看订单'
      this.readonlyInput = true
      this.order = {
        id: val.id,
        code: val.code,
        insideCode: val.insideCode,
        customer: val.customer,
        deliveryTime: val.deliveryTime
        // amount: val.amount,
        // imageAmount: val.imageAmount,
        // partsAmount: val.partsAmount,
        // price: val.price
      }
      this.order.product = []
      if (
        val.productList == null ||
					val.productList == undefined ||
					val.productList == ''
      ) {
        this.productSelectItem = []
      } else {
        // this.productSelectItem = val.productList
        for (let i = 0; i < val.productList.length; i++) {
          if (val.productList[i]) {
            this.order.product.push(val.productList[i].insideCode)
            this.productSelectItem.push(val.productList[i])
          }
        }
        console.log(this.order.product)
      }
    },
    upload(val) {
      this.readonlyInput = false
      user.orderDetail({
        id: val.id
      }).then((response) => {
        this.order = {
          id: val.id,
          code: response.code,
          insideCode: response.insideCode,
          customer: response.customer,
          deliveryTime: response.deliveryTime
          // amount: response.amount,
          // imageAmount: response.imageAmount,
          // partsAmount: response.partsAmount,
          // price: response.price
        }
        this.order.product = []
        if (
          response.productList == null ||
						response.productList == undefined ||
						response.productList == ''
        ) {
          this.productSelectItem = []
        } else {
          // this.productSelectItem = val.productList
          for (let i = 0; i < response.productList.length; i++) {
            if (response.productList[i]) {
              this.order.product.push(
                response.productList[i].insideCode
              )
              this.productSelectItem.push(
                response.productList[i]
              )
            }
          }
          console.log(this.order.product)
        }
        this.dialogFormVisible = true
        this.dialogFormValue = '修改订单'
      })
    },
    httpRequest() {},
    importFile() {
      this.dialogFileUpload.show = true
      this.dialogFileUpload.disabled = false
      this.dialogFileUpload.type = IMPORT_EXECL
      this.dialogFileUpload.row = {}
    },
    beforeUploadFile(file) {
      const {
        zipType,
        excelType,
        isImportExecl,
        isUploadZip,
        dialogFileUpload: { row }
      } = this
      const fileName = file.name
        .substring(file.name.lastIndexOf('.') + 1)
        .toLowerCase()

      // 验证excel类型
      if (isImportExecl) {
        if (!excelType.includes(fileName)) {
          this.$message({
            message: `上传文件只能是 ${excelType.join('、')}格式!`,
            type: 'warning'
          })
          return false
        }
      }

      // 验证压缩包类型
      if (isUploadZip) {
        if (!zipType.includes(fileName)) {
          this.$message({
            message: `上传文件只能是 ${zipType.join('、')}格式!`,
            type: 'warning'
          })
          return false
        }
      }

      const formData = new FormData()
      formData.append('file', file)
      isUploadZip && formData.append('orderId', row.id)

      this.dialogFileUpload.fileName = file.name
      this.dialogFileUpload.formData = formData
    },
    closeUploadFileDialog() {
      this.dialogFileUpload.fileName = ''
      this.dialogFileUpload.formData = null
      this.dialogFileUpload.show = false
      this.listOrder()
    },
    removeFile() {
      this.dialogFileUpload.fileName = ''
      this.dialogFileUpload.formData = null
    },
    confirmUpload() {
      const {
        isImportExecl,
        isUploadZip,
        dialogFileUpload: { row, fileName, formData }
      } = this
      if (isUploadZip && !row.id) return false
      if (!fileName || !formData) return false

      this.dialogFileUpload.loading = true

      const uploadPromise = isImportExecl
        ? user.backendImport(formData)
        : user.uploadZip(formData)

      uploadPromise.then((res) => {
        this.dialogFileUpload.loading = false
        this.dialogFileUpload.disabled = true
        this.$message.success(res.message || '导入成功')
        this.closeUploadFileDialog()
      })
    }
  }
}
</script>
<style>
.el-table .warning-row {
	background: #ff02027a;
}

.el-upload__tip {
	color: #999;
	font-size: 12px;
}

.the-file {
	position: relative;
	display: inline-block;
}

.the-file-delete {
	margin-left: 10px;
}
</style>
